package com.lijing.mock.manager;

import com.lijing.mock.model.bo.MockRegionBO;
import com.lijing.mock.model.ServerResult;
import com.lijing.mock.model.bo.UrlRandomBO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * mock 随机管理器
 * @author by lijing
 * @date 2019/12/2 0002 16:49
 */
@Slf4j
@Component
public class MockRandomManager {

    private final UrlMockManager urlMockManager;

    private final LocalCacheManager localCacheManager;

    public MockRandomManager(UrlMockManager urlMockManager,LocalCacheManager localCacheManager) {
        this.urlMockManager = urlMockManager;
        this.localCacheManager = localCacheManager;
    }

    /**
     * 获取连接相关的随机结果
     * @param urlId 连接url Id
     * @return 随机mock结果
     */
    public ServerResult<String> mockRandom(String urlId){
        UrlRandomBO urlRandom = localCacheManager.getUrlRandom(urlId);
        if(urlRandom==null){
            return new ServerResult<>(Boolean.FALSE,"无法找到相关mock结果配置信息",null);
        }
        MockRegionBO region = getRandomRegion(urlRandom);
        List<String> list = region.getMockDataList();
        String result = getRandomListData(list);
        if(result==null){
            return new ServerResult<>(Boolean.FALSE,"无法找到相关mock结果配置信息",null);
        }
        return new ServerResult<>(Boolean.TRUE,null,result);
    }



    /**
     * 获取随机结果类型
     * @param urlRandomBO url随机对象
     * @return 随机结果类型
     */
    private MockRegionBO  getRandomRegion(UrlRandomBO urlRandomBO){
        int random = new Random().nextInt(urlRandomBO.getTotalWeight());
        return urlRandomBO.getUrlId(random);
    }

    /**
     * 获取随机结果数据
     * @param dataList 参与随机的结果数据集合
     * @return 随机结果数据
     */
    private String  getRandomListData(List<String> dataList){
        if(dataList==null||dataList.size()==0){
            return null;
        }
        if(dataList.size()==1){
            return dataList.get(0);
        }
        int random = new Random().nextInt(dataList.size());
        return dataList.get(random);
    }






}
